# encoding: utf-8
"""
图片处理
@author: xiao nian
@contact: xiaonian030@163.com
@date: 2022-09-08
"""

__copyright__ = "Copyright (c) (2022-2022) QF Inc. All Rights Reserved"
__author__ = "Xiao Nian"
__date__ = "2022-09-10:14:13:24"
__version__ = "1.0.0"

import os
import requests
from snowflake import SnowflakeGenerator
import logging
import datetime
import numpy as np
from PIL import Image
from service.image_hash import average_hash
import cv2
from my_fake_useragent import UserAgent


def change_url(url):
    try:
        index = url.rindex('/')
        url_prefix = url[0:index]
        size = url[index + 1:]
        if url_prefix == '':
            url = ''
        elif size.isdigit():
            url = url_prefix + '/0'
    except:
        url = ''
    return url


def download_image(url, file_path):
    """
    下载图片方法
    """
    ua = UserAgent(family='chrome')
    headers = {"User-Agent": ua.random()}
    current_date = datetime.datetime.now().strftime('%Y-%m-%d')
    generator = SnowflakeGenerator(42)
    unique_id = next(generator)
    file_path = file_path + "/" + current_date
    if not os.path.exists(file_path):
        os.makedirs(file_path)
    local_file = str(file_path) + '/' + str(unique_id) + '.jpeg'
    response = requests.request(
        method='GET',
        url=url,
        headers=headers,
        stream=True)
    if response.status_code == 200:
        # 创建文件保存图片
        with open(local_file, 'wb') as f:
            # 将图片字节码写入创建的文件中
            f.write(response.content)
    else:
        logging.error('图片下载失败 [url] ' + str(url))
    return local_file


def get_hash_value(local_file, shape):
    img = cv2.imread(local_file)
    head_size = round(np.sum(img)/10000000)
    head_id = int(average_hash(img, shape), 2)
    if head_id < 1:
        head_id = 1
    if head_size < 1:
        head_size = 1
    return head_id, head_size


def get_size_value(local_file):
    try:
        file_hand = open(local_file, 'rb')
        byte100 = 0
        while True:
            read_buffer = file_hand.read(1024)
            if not read_buffer:
                break
            byte100 = byte100 + len(read_buffer)
        byte100 = int(byte100 / 100)
        file_hand.close()
    except:
        byte100 = 0
    return byte100


def get_image_info(local_file, shape):
    """
    图片信息
    """
    info = {
        'byte100': 0,
        'width': 0,
        'height': 0,
        'hash_value': 0
    }
    try:
        file_hand = open(local_file, 'rb')
        byte100 = 0
        while True:
            read_buffer = file_hand.read(1024)
            if not read_buffer:
                break
            byte100 = byte100 + len(read_buffer)
        info['byte100'] = int(byte100 / 100)
        file_hand.close()
    except:
        pass
    try:
        image_info = Image.open(local_file)
        info['width'] = int(image_info.width)
        info['height'] = int(image_info.height)
    except:
        pass
    info['hash_value'] = get_hash_value(local_file, shape)
    return info
